/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import bean.LoginActionFormBean;
import bean.MainScheduleTask;
import dao.ActivityHistoryCrud;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.LogFile;
import model.MainTaskModel;
import model.OSDetector;
import model.ScheduledTaskLinux;
import model.ScheduledTaskWindows;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import pojo.Activities;
import pojo.ActivityHistory;
import pojo.CMST;

/**
 *
 * @author A7med Kotb
 */
//class that handles main schedule task data
public class MainScheduleTaskAction extends org.apache.struts.actions.DispatchAction {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    //Create Main Schedule Task
    public ActionForward Create(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        MainScheduleTask mst = (MainScheduleTask) form;
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        String type = request.getParameter("type");
        CMST cmst = new CMST();
        cmst.setTaskName(mst.getTaskName());
        cmst.setSchedule(mst.getSchedule());
        cmst.setModifier(mst.getModifier());
        cmst.setStartDate(mst.getStartDated());
        cmst.setStartTime(mst.getStartTime());
        if (mst.getSchedule().equalsIgnoreCase("hourly") || mst.getSchedule().equalsIgnoreCase("daily")) {
            mst.setDay(null);
        }
        if (mst.getDay() != null) {
            String[] selectedDays = mst.getDay();
            String days = "";
            for (int i = 0; i < selectedDays.length; i++) {
                days += selectedDays[i] + ",";
            }
            int strlen = days.length();
            int lastindex = strlen - 1;
            String taskdays = days.substring(0, lastindex);
            cmst.setDay(taskdays);
        } else {
            cmst.setDay(null);
        }
        if (mst.getMonth() != null) {
            String[] selectedMonths = mst.getMonth();
            String months = "";
            for (int i = 0; i < selectedMonths.length; i++) {
                months += selectedMonths[i] + ",";
            }
            int monthslen = months.length();
            int lastmonthsindex = monthslen - 1;
            String taskmonths = months.substring(0, lastmonthsindex);
            cmst.setMonth(taskmonths);
        } else {
            cmst.setMonth(null);
        }
        cmst.setIsEnable(true);
        cmst.setIsRunning(false);
        cmst.setTaskType(type);
        MainTaskModel mtm = new MainTaskModel(getDataSource(request, "MyDS").getConnection());
        boolean adddbresult = mtm.add(cmst);
        boolean addresult = false;
        if (OSDetector.isWindows()) {
            addresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).createmaintask(cmst, cmst.getTaskType());
        }
        if (OSDetector.isUnix()) {
            new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).createmaintask(cmst, cmst.getTaskType());
        }
        boolean logresult = activityHistory("Add MainTask", request, mst.getTaskName());
        return mapping.findForward(SUCCESS);
    }

    //Method to display Media Task
    public ActionForward displayMedia(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = null;
        CMST mytaskm = new MainTaskModel(getDataSource(request, "MyDS").getConnection()).getMediaTask();
        System.out.println("Media Task Name ......................" + mytaskm.getTaskName());
        if ((mytaskm.getTaskName()).equalsIgnoreCase("No Task Found")) {
            request.setAttribute("type", "media");
            forward = mapping.findForward("notfound");
        } else {
            request.setAttribute("mytask", mytaskm);
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            String reportDate = df.format(mytaskm.getStartDate());
            System.out.println("reportDate is Equal to " + reportDate);
            request.setAttribute("startdate", reportDate);
            forward = mapping.findForward("found");
        }
        return forward;
    }

    //method to display book Main Task
    public ActionForward displayBook(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = null;
        CMST mytaskb = new MainTaskModel(getDataSource(request, "MyDS").getConnection()).getBookTask();
        System.out.println("Book Task Name ......................" + mytaskb.getTaskName());
        if ((mytaskb.getTaskName()).equalsIgnoreCase("No Task Found")) {
            request.setAttribute("type", "book");
            forward = mapping.findForward("notfound");
        } else {
            request.setAttribute("mytask", mytaskb);
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            String reportDate = df.format(mytaskb.getStartDate());
            System.out.println("reportDate is Equal to " + reportDate);
            request.setAttribute("startdate", reportDate);
            forward = mapping.findForward("found");
        }
        return forward;
    }

    //method to update main schedule task data
    public ActionForward Update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        MainScheduleTask mst = (MainScheduleTask) form;
        System.out.println("Now in Update Method");
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        CMST cmst = new CMST();
        cmst.setTaskName(mst.getTaskName());
        cmst.setSchedule(mst.getSchedule());
        cmst.setModifier(mst.getModifier());
        cmst.setStartDate(mst.getStartDated());
        cmst.setStartTime(mst.getStartTime());
        if (mst.getDay() != null) {
            String[] selectedDays = mst.getDay();
            String days = "";
            for (int i = 0; i < selectedDays.length; i++) {
                days += selectedDays[i] + ",";
            }
            int strlen = days.length();
            int lastindex = strlen - 1;
            String taskdays = days.substring(0, lastindex);
            cmst.setDay(taskdays);
        } else {
            cmst.setDay(null);
        }
        cmst.setTaskType(mst.getTaskType());
        MainTaskModel mtm = new MainTaskModel(getDataSource(request, "MyDS").getConnection());
        boolean logresult = activityHistory("Update Main Task", request, mst.getTaskName());
        boolean updatedbresult = mtm.update(cmst);
        boolean deleteresult = false;
        boolean createresult = false;
        if (OSDetector.isWindows()) {
            deleteresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).deleteMainTask(mst.getTaskName());
            createresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).createmaintask(cmst, mst.getTaskType());
        }
        if (OSDetector.isUnix()) {
            deleteresult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).deleteMainTask(mst.getTaskName());
            createresult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).createmaintask(cmst, mst.getTaskType());
        }
        if (updatedbresult == true && deleteresult == true && createresult == true) {
            LogFile.log(loginbean.getUserName(), " updated the following main schedule task data  " + mst.getTaskName());
        } else {
            LogFile.log(" System ", " failed to update data this main schedule task  " + mst.getTaskName());
        }
        if (logresult == true) {
            LogFile.log(" System ", " Logged the operation of updating that main schedule task " + mst.getTaskName());
        } else {
            LogFile.log(" System ", " failed to log the operation of updating that main schedule task " + mst.getTaskName());
        }
        return mapping.findForward("update");
    }

    //method to delete main schedule task
    public ActionForward Delete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("Now in Delete Method");
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        MainScheduleTask mst = (MainScheduleTask) form;
        CMST cmst = new CMST();
        cmst.setTaskName(mst.getTaskName());
        cmst.setSchedule(mst.getSchedule());
        cmst.setModifier(mst.getModifier());
        cmst.setStartDate(mst.getStartDated());
        cmst.setStartTime(mst.getStartTime());
        if (mst.getDay() != null) {
            String[] selectedDays = mst.getDay();
            String days = "";
            for (int i = 0; i < selectedDays.length; i++) {
                days += selectedDays[i] + ",";
            }
            int strlen = days.length();
            int lastindex = strlen - 1;
            String taskdays = days.substring(0, lastindex);
            cmst.setDay(taskdays);
        } else {
            cmst.setDay(null);
        }
        cmst.setTaskType(mst.getTaskType());
        MainTaskModel mtm = new MainTaskModel(getDataSource(request, "MyDS").getConnection());
        boolean logresult = activityHistory("Delete Main Task", request, mst.getTaskName());
        boolean deleteresult = false;
        if (OSDetector.isWindows()) {
            deleteresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).deleteMainTask(mst.getTaskName());
        }
        if (OSDetector.isUnix()) {
            deleteresult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).deleteMainTask(mst.getTaskName());
        }
        boolean deletedbresult = mtm.delete(cmst);
        if (deletedbresult == true && deleteresult == true) {
            LogFile.log(loginbean.getUserName(), " deleted the following main schedule task data  " + mst.getTaskName());
        } else {
            LogFile.log(" System ", " failed to delete data of this main schedule task  " + mst.getTaskName());
        }
        if (logresult == true) {
            LogFile.log(" System ", " Logged the operation of deleting that main schedule task " + mst.getTaskName());
        } else {
            LogFile.log(" System ", " failed to log the operation of deleting that main schedule task " + mst.getTaskName());
        }
        return mapping.findForward("delete");
    }

    //enable main schedule task
    public ActionForward Enable(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = new ActionForward();
        MainScheduleTask mst = (MainScheduleTask) form;
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        boolean enableResult = false;
        if (OSDetector.isWindows()) {
            enableResult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).enableMainTask(mst.getTaskName());
        }
        if (OSDetector.isUnix()) {
            enableResult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).enableMainTask(mst.getTaskName());
        }
        if (mst.getTaskType().equalsIgnoreCase("book")) {
            forward = displayBook(mapping, form, request, response);
        }
        if (mst.getTaskType().equalsIgnoreCase("media")) {
            forward = displayMedia(mapping, form, request, response);
        }
        return forward;
    }

    //disable main task
    public ActionForward Disable(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = new ActionForward();
        MainScheduleTask mst = (MainScheduleTask) form;
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        boolean disableResult = false;
        if (OSDetector.isWindows()) {
            disableResult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).disableMainTask(mst.getTaskName());
        }
        if (OSDetector.isUnix()) {
            disableResult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).disableMainTask(mst.getTaskName());
        }
        if (mst.getTaskType().equalsIgnoreCase("book")) {
            forward = displayBook(mapping, form, request, response);
        }
        if (mst.getTaskType().equalsIgnoreCase("media")) {
            forward = displayMedia(mapping, form, request, response);
        }
        return forward;
    }

    //method to start schedule task now
    public ActionForward Start(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = new ActionForward();
        MainScheduleTask mst = (MainScheduleTask) form;
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        boolean startresult = false;
        if (OSDetector.isWindows()) {
            startresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).startMainTask(mst.getTaskName());
        }
        if (OSDetector.isUnix()) {
            startresult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).startMainTask(mst.getTaskName());
        }
        if (mst.getTaskType().equalsIgnoreCase("book")) {
            forward = displayBook(mapping, form, request, response);
        }
        if (mst.getTaskType().equalsIgnoreCase("media")) {
            forward = displayMedia(mapping, form, request, response);
        }
        return forward;
    }
    //Add Activity to Activity History

    public boolean activityHistory(String activityName, HttpServletRequest request, String maintaskname) {
        boolean check = false;
        try {
            LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
            ActivityHistory log = new ActivityHistory();
            log.setAdminName(loginbean.getUserName());
            log.setProviderName(maintaskname);
            log.setStatus("Success");
            log.setLiveServer(null);
            ActivityHistoryCrud ahc = new ActivityHistoryCrud(getDataSource(request, "MyDS").getConnection());
            Activities act = ahc.getByName(activityName);
            log.setActivities(act);
            log.setActivityName(act.getName());
            check = ahc.add(log);
        } catch (SQLException ex) {
            check = false;
            LogFile.log(" System ", " encountered the following error while trying to Log that main task activity");
            Logger.getLogger(STOperations.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }
}
